package com.zte.market.control;

import com.zte.login.pojo.Users;
import com.zte.market.pojo.Custom;
import com.zte.market.pojo.Order;
import com.zte.market.pojo.Orderdetails;
import com.zte.market.pojo.otherPojo.CBrand;
import com.zte.market.pojo.otherPojo.CProduct;
import com.zte.market.pojo.otherPojo.CType;
import com.zte.market.pojo.otherPojo.DateTemp;
import com.zte.market.service.CustomService;
import com.zte.market.service.OrderService;
import com.zte.market.service.OrderdetailsService;
import com.zte.market.service.otherService.CBrandService;
import com.zte.market.service.otherService.CProductService;
import com.zte.market.service.otherService.CTypeService;
import com.zte.util.PageModel;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 许月
 * @Date: 2022/10/05/19:19
 */
@Controller
@RequestMapping("/order")
@SessionAttributes("orderPage")
public class OrderController {
    @Autowired
    private OrderService orderService; //订单 service

    @Autowired
    private OrderdetailsService orderdetailsService;  //订单详情 service

    @Autowired
    private CBrandService cBrandService; //品牌 service

    @Autowired
    private CTypeService cTypeService;  //类型 service

    @Autowired
    private CProductService cProductService; //商品 service

    @Autowired
    private CustomService customService;

    /**
     * 分页查询
     *
     * @param orderid    订单号
     * @param customname 客户名
     * @param startDate  最早时间
     * @param endDate    最晚时间
     * @param minPrice   最低金额
     * @param maxPrice   最高金额
     * @param status     状态
     * @param pageNum    当前页
     * @param pageSize   页面尺寸
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/queryfenye")
    public String queryfenye(String orderid, String customname, @RequestParam(value = "startDate", defaultValue = "")String startDate,
                             @RequestParam(value = "endDate", defaultValue = "")String endDate, Double minPrice,
                             Double maxPrice, String status, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "7") Integer pageSize, Model model, HttpSession session) {
        //获取登录用户信息
        Users user = (Users) session.getAttribute("user");

        String startDate1 = null;
        if (startDate != null && !"".equals(startDate)) {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date d = null;
            try {
                d = format.parse(startDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            DateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            startDate1 = dateformat.format(d);

        }
        String endDate1 = null;
        if (endDate != null && !"".equals(endDate)) {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date d = null;
            try {
                d = format.parse(endDate);
            } catch (Exception e) {
                e.printStackTrace();
            }
            DateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            endDate1 = dateformat.format(d);
        }


        DateTemp dateTemp = new DateTemp();
        dateTemp.setStartDate(startDate1);
        dateTemp.setEndDate(endDate1);
        List<Integer> customIdList = customService.queryCustomIdListByCustomname(customname);
        List<Order> orderList = orderService.getAllByParams(orderid, customIdList,dateTemp, minPrice, maxPrice, status);

        List<Order> orderListTemp = new ArrayList<>();
        if (user.getJobId() == 3) {
//            判断是否为普通员工
            for (Order order : orderList) {

                if (order.getOperatorid() == user.getUid()) {
                    orderListTemp.add(order);
                }
            }
        } else {
            orderListTemp = orderList;
        }
        PageModel<Order> orderPage = orderService.queryByPage(orderListTemp, pageSize, pageNum);
        model.addAttribute("orderPage", orderPage);
//        回显
        model.addAttribute("orderid", orderid);  //订单编号输入框
        model.addAttribute("customname", customname); //客户姓名输入框
        model.addAttribute("startDate", startDate);//开始时间输入框
        model.addAttribute("endDate", endDate);   //最终时间输入框
        model.addAttribute("minPrice", minPrice);  //最低金额输入框
        model.addAttribute("maxPrice", maxPrice);   //最高金额输入框
        model.addAttribute("status", status);        //状态选择栏

        return "market/order/orderList";
    }

    /**
     * 跳转到添加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        List<CBrand> brandList = cBrandService.getAll();
        model.addAttribute("brandList", brandList);
        return "market/order/orderAdd";
    }

    /**
     * 响应商品的类型给前端
     *
     * @param brandId
     * @return
     */
    @RequestMapping("/queryCTypeListByAjax")
    @ResponseBody
    public List<CType> queryCTypeListByAjax(Integer brandId) {
        List<CType> cTypeList = cTypeService.getAllByBrandId(brandId);
        return cTypeList;
    }

    /**
     * 响应商品列表给前端
     *
     * @param typeId
     * @return
     */
    @RequestMapping("/queryProductListByAjax")
    @ResponseBody
    public List<CProduct> queryProductListByAjax(Integer typeId) {
        List<CProduct> productList = cProductService.getByTypeId(typeId);
        return productList;
    }

    /**
     * 响应商品的单价给前端
     *
     * @param productId
     * @return
     */
    @RequestMapping("/queryProductPriceByAjax")
    @ResponseBody
    public Double queryProductPriceByAjax(Integer productId) {
        CProduct cProduct = cProductService.getByProductId(productId);
        Double price = cProduct.getProductPrice();
        return price;
    }

    /**
     * 用于返回输入用户是否存在
     * @param customname
     * @return
     */
    @RequestMapping("/queryCustomIsExist")
    @ResponseBody
    public Integer queryCustomIsExist(String customname) {
        List<Integer> customIdList = customService.queryCustomIdListByCustomnameAjax(customname);
        Integer customId = 0;
        if(customIdList.size() >0){
            customId = customIdList.get(0);
        }

        return customId;
    }

    /**
     * 添加订单
     *
     * @param order
     * @param ordertimeStr
     * @param session
     * @return
     */
    @RequestMapping("/addOrder")
    public String addOrder(Order order, String ordertimeStr, HttpSession session, HttpServletRequest request) {
        System.out.println(ordertimeStr);//
       /* Date ordertime = new Date(System.currentTimeMillis());
        if (ordertimeStr != null && !"".equals(ordertimeStr)) {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd Hh:mm:ss");
            java.util.Date d = null;
            try {
                d = format.parse(ordertimeStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ordertime = new java.sql.Date(d.getTime());
        }
        //向订单数据中补充 订单时间数据
        order.setOrdertime(ordertime);*/
        Date  ordertime = new Date(System.currentTimeMillis());
        order.setOrdertime(ordertime);
        //添加订单操作
        Integer result1 = orderService.addByOrder(order);
        System.out.println(result1);//

        //获取订单详情数据
        String[] productIds = request.getParameterValues("productId");//商品id数组 Integer
        String[] purchaseNums = request.getParameterValues("purchaseNum");//商品 数量数组 Integer
        String[] proprices = request.getParameterValues("proprice"); //商品单价数组 Double
        String[] prototals = request.getParameterValues("prototal");//商品 总金额数组 Double

        //将订单详情数据进行封装
        List<Orderdetails> orderdetailsList = new ArrayList<>();
        for (int i = 0; i < productIds.length; i++) {
            if (productIds[i] != null && !"".equals(productIds[i])) {
                if (purchaseNums[i] != null && !"".equals(purchaseNums[i]) && Integer.parseInt(purchaseNums[i]) != 0) {
                    Orderdetails orderdetails = new Orderdetails();
                    orderdetails.setProductId(Integer.parseInt(productIds[i])); //商品id
                    orderdetails.setPurchaseNum(Integer.parseInt(purchaseNums[i])); //商品数量
                    orderdetails.setProprice(Double.parseDouble(proprices[i]));  //商品单价
                    orderdetails.setPrototal(Double.parseDouble(prototals[i]));  //商品总金额
                    orderdetails.setOrderId(order.getOrderid());  //订单编号
                    orderdetailsList.add(orderdetails);
                }
            }
        }
        //添加订单详情操作
        Integer result2 = orderdetailsService.addByOrderdetailsList(orderdetailsList);

        PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
        int pageNum = orderPage.getPageNum();
        return "redirect:/order/queryfenye?pageNum=" + pageNum;

    }

    /**
     * 跳转到查看详情页面
     * @param orderid
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/toshow")
    public String toshow(String orderid, Model model, HttpSession session) {
        Order order = orderService.getByOrderId(orderid);
        if (order == null) {
            PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
            int pageNum = orderPage.getPageNum();
            return "redirect:/order/queryfenye?pageNum=" + pageNum;
        }
        model.addAttribute("order", order);
        List<CBrand> brandList = cBrandService.getAll();
        model.addAttribute("brandList", brandList);
        return "market/order/orderView";
    }

    /**
     * 跳转到修改页面
     * @param orderid
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/toupdate")
    public String toupdate(String orderid, Model model, HttpSession session) {
        Order order = orderService.getByOrderId(orderid);
        if (order == null) {
            PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
            int pageNum = orderPage.getPageNum();
            return "redirect:/order/queryfenye?pageNum=" + pageNum;
        }
        model.addAttribute("order", order);
        List<CBrand> brandList = cBrandService.getAll();
        model.addAttribute("brandList", brandList);
        return "market/order/orderUpdate";
    }

    /**
     * 进行修改操作订单
     * @param orderid
     * @param ordermoney
     * @param session
     * @param request
     * @return
     */
    @RequestMapping("/updateOrder")
    public String updateOrder(String orderid, Double ordermoney, HttpSession session, HttpServletRequest request) {
        Order order = new Order();
        order.setOrderid(orderid);
        order.setOrdermoney(ordermoney);
        //修改订单操作
        Integer result1 = orderService.updateByOrder(order);
        System.out.println(result1);//

        //获取订单详情数据
        String[] productIds = request.getParameterValues("productId");//商品id数组 Integer
        String[] detailsIds = request.getParameterValues("detailsId");//商品id数组 Integer
        String[] purchaseNums = request.getParameterValues("purchaseNum");//商品 数量数组 Integer
        String[] proprices = request.getParameterValues("proprice"); //商品单价数组 Double
        String[] prototals = request.getParameterValues("prototal");//商品 总金额数组 Double
//将订单详情数据进行封装
        List<Orderdetails> orderdetailsList = new ArrayList<>();
        for (int i = 0; i < productIds.length; i++) {
            if (productIds[i] != null && !"".equals(productIds[i])) {
                if (purchaseNums[i] != null && !"".equals(purchaseNums[i]) && Integer.parseInt(purchaseNums[i]) != 0) {
                    Orderdetails orderdetails = new Orderdetails();
                    orderdetails.setProductId(Integer.parseInt(productIds[i])); //商品id
                    if(detailsIds[i] != null && !"".equals(detailsIds[i])){
                        orderdetails.setDetailsId(Integer.parseInt(detailsIds[i])); // 订单详情id
                    }
                    orderdetails.setPurchaseNum(Integer.parseInt(purchaseNums[i])); //商品数量
                    orderdetails.setProprice(Double.parseDouble(proprices[i]));  //商品单价
                    orderdetails.setPrototal(Double.parseDouble(prototals[i]));  //商品总金额
                    orderdetails.setOrderId(order.getOrderid());  //订单编号
                    orderdetailsList.add(orderdetails);
                }
            }
        }
        //先删除所有（跟订单号有关的）订单详情
        Integer delete = orderdetailsService.deleteByOrderId(orderid);
        //添加订单详情操作
        if (orderdetailsList.size() > 0) {
            Integer result2 = orderdetailsService.addByOrderdetailsList(orderdetailsList);
            System.out.println(result2);//
        } else {
            //如果订单的详情为空，就把定单的数据也删除掉
            orderService.deleteByOrderid(orderid);
        }

        PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
        int pageNum = orderPage.getPageNum();
        return "redirect:/order/queryfenye?pageNum=" + pageNum;
    }


    /**
     * 进行订单的审核分配
     * @param fenPeiOrderId
     * @param checkid
     * @param session
     * @return
     */
    @RequestMapping("/toFenPei")
    public String toFenPei(String fenPeiOrderId,Integer checkid,HttpSession session){
        Order order = new Order();
        order.setOrderid(fenPeiOrderId); //订单id
        order.setCheckid(checkid);      //被分配者的id
        order.setStatus("审核中");       //审核状态需要改变
        orderService.updateByOrder(order);//修改操作(向订单数据中添加审核人id)

        PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
        int pageNum = orderPage.getPageNum();
        return "redirect:/order/queryfenye?pageNum=" + pageNum;
    }

    /**
     * 执行删除操作，并返回订单页面
     * @param orderid
     * @param session
     * @return
     */
    @RequestMapping("/todelete")
    public String todelete(String orderid,HttpSession session){
        //先删除与该订单相关所有的订单详情数据
        orderdetailsService.deleteByOrderId(orderid);
        //再来删除订单数据
        orderService.deleteByOrderid(orderid);
        PageModel<Order> orderPage = (PageModel<Order>) session.getAttribute("orderPage");
        int pageNum = orderPage.getPageNum();
        return "redirect:/order/queryfenye?pageNum=" + pageNum;

    }


}
